package org.pushforward.iwillsurvive.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.pushforward.iwillsurvive.helpers.Utils;

/**
 * @author Sabre Runner
 * 
 * Reads attributes from session and sends them back as test.
 * Operation "[...]/SessionReader?attrname=[enter attribute name here]"
 * The value will be returned as string.
 */
@WebServlet(description = "Reads back session attributes", urlPatterns = { "/SessionReader" })
public class SessionReader extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SessionReader() 
    {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		try
		{
			PrintWriter writer = response.getWriter();
			HttpSession session = request.getSession();
			String attributeName = request.getParameter("attrname");
			String attributeValue = session.getAttribute(attributeName).toString(); 

			Utils.Log("Returning attribute: " + attributeName + " = " + attributeValue);
			writer.write(attributeValue);
		} catch (Exception e)
		{
			Utils.Log("Error getting value of attribute " + request.getParameter("attrname"));
			response.setStatus(500);
			response.getWriter().write("null");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		if (request.getParameter("action").equalsIgnoreCase("clear"))
		{
			request.getSession().invalidate();
		}
	}

}
